package com.demo.jingxi.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.jingxi.dao.UserMapper;
import com.demo.jingxi.dao.XUserRoleMapper;
import com.demo.jingxi.pojo.User;
import com.demo.jingxi.pojo.XUserRole;
import com.demo.jingxi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private XUserRoleMapper xUserRoleMapper;
    @Override
    public Map<String, String> login(User user) {
        //实现登录功能，输入用户名和密码，匹配用户
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,user.getUsername()).eq(User::getPassword,user.getPassword());
          user =  this.baseMapper.selectOne(lambdaQueryWrapper);

          Map<String,String> map = null;
          if(user != null){
           map = new HashMap<>();
           String token = "UUID" + UUID.randomUUID();
           //设置为三十分钟
           redisTemplate.opsForValue().set(token,user,30, TimeUnit.MINUTES);
           map.put("token",token);

          }


        return map;
    }
    @Override
    public Map<String, Object> getUserInfo(String token) {
        // 从redis查询token
        Object obj = redisTemplate.opsForValue().get(token);
        // 反序列化
        User user = JSON.parseObject(JSON.toJSONString(obj),User.class);
        if(user != null){
            Map<String, Object> data =  new HashMap<>();
            data.put("name",user.getUsername());
            data.put("avatar",user.getAvatar());
            List<String> roleList = this.getBaseMapper().getRoleNamesByUserId(user.getId());
            data.put("roles", roleList);
            return data;
        }
        return null;
    }

    @Override
    public void addUser(User user) {
        String password = user.getPassword();
        // 对密码进行加密
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString(b & 0xff);
                if (hex.length() == 1) {
                    sb.append("0");
                }
                sb.append(hex);
            }
            user.setPassword(sb.toString());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        this.save(user);
        List<Integer> roleIdList = user.getRoleIdList();
        if ( roleIdList != null) {
            for (Integer roleId : roleIdList) {
              xUserRoleMapper.insert(new XUserRole(null,user.getId(),roleId));
            }

        }
    }
    @Override
    public void updateUser(User user) {
        this.updateById(user);
        LambdaQueryWrapper<XUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XUserRole::getUserId,user.getPhone());
        xUserRoleMapper.delete(queryWrapper);
        List<Integer> roleIdList = user.getRoleIdList();
        if (roleIdList != null){
            for (Integer roleId : roleIdList) {
                xUserRoleMapper.insert(new XUserRole(null,user.getId(),roleId));
            }
        }
    }
    @Override
    public void logut(String token) {
        redisTemplate.delete(token);
    }

    @Override
    public User getUserId(Integer id) {
        User user = this.getById(id);
        LambdaQueryWrapper<XUserRole> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.eq(XUserRole::getUserId,id);
        List<XUserRole> xUserRoles = xUserRoleMapper.selectList(queryWrapper);
        List<Integer> roleIdList = xUserRoles.stream().map(xUserRole -> {
            return xUserRole.getRoleId();
        }).collect(Collectors.toList());

        user.setRoleIdList(roleIdList);
        return user;


    }



    @Override
    public void deleteById(Integer id) {
         this.removeById(id);
        LambdaQueryWrapper<XUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XUserRole::getUserId,id);
    }

}
